<template>
  <div class="app-container">
    <el-form v-if="false"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品id" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品代码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['finace:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['finace:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['finace:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['finace:product:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="single"
          icon="CirclePlusFilled"
          @click="handleCreateTable1"
          v-hasPermi="['finace:product:export']"
          title="创建gen_table"
          >建表1</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="single"
          icon="CirclePlusFilled"
          @click="handleCreateTable2"

          v-hasPermi="['finace:product:export']"
          title="创建gen_table_column"
          >建表2</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dbList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="数据源名称"
        align="left"
        prop="dsName"
        :show-overflow-tooltip=true
        width="100"
      />
      <el-table-column
        label="数据源类型"
        width="100"
        align="left"
        prop="dbType"
        :show-overflow-tooltip=true
      />
      <el-table-column
        label="驱动类"
        align="left"
        prop="driverClassName"
        width="150"
        :show-overflow-tooltip=true
      />
      <el-table-column
        label="jdbcUrl"
        align="left"
        prop="jdbcUrl"
        :show-overflow-tooltip=true
      />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改product_func对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="dbRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据源名称" prop="dsName">
          <el-input v-model="form.dsName" placeholder="请输入产品代码" />
        </el-form-item>
        <!-- <el-form-item label="产品类型" prop="productType">
            <el-input v-model="form.productType" placeholder="请输入产品类型" />
        </el-form-item> -->
        <el-form-item label="数据源类型" prop="dbType">
          <el-select v-model="form.dbType" placeholder="请选择数据源类型">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
            show-password="true"
          />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" @input="handleDbPropertyChange"  />
        </el-form-item>
        <el-form-item label="数据库IP" prop="dbIp">
          <el-input v-model="form.dbIp" placeholder="请输入数据库IP" @input="handleDbPropertyChange"  />
        </el-form-item>
        <el-form-item label="jdbcUrl" prop="jdbcUrl">
          <el-input v-model="form.jdbcUrl" placeholder="请输入jdbcUrl" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    {{ msg }}
  </div>
</template>

<script setup lang="ts">
import { listDs, addDs, updateDs } from "@/app/appcommon/api/dynamicDB/datasourceMgr";
import { createTable } from "@/app/appcommon/api/tool/gen2";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import gen_table from "../gen/gen_table";
import gen_table_column from "../gen/gen_table_column";
const msg = ref("DBMgr");

//   listDb().then(res => {
//     console.log(res)
//     msg.value = res.rows
//   })

const { proxy } = getCurrentInstance();

const dbList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const selectedValue = ref(""); // 绑定的值
const options = ref([
  { label: "mysql", value: "com.mysql.cj.jdbc.Driver" },
  { label: "sqlServer", value: "com.microsoft.sqlserver.jdbc.SQLServerDriver" },
]);
const data = reactive({
  form: {
    dbIp:'127.0.0.1',
    dbName:"db_test",
    jdbcUrl: "jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&socketTimeout=60000",

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    productCode: null,
    productName: null,
    productType: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询product_func列表 */
function getList() {
  loading.value = true;
  listDs(queryParams.value)
    .then((response) => {
      dbList.value = response.rows ||[];
      total.value = response.total || 0;
      loading.value = false;
    })
    .catch((err) => {
      console.log("error", err);
      loading.value = false;
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dbIp: '127.0.0.1',
    dbName: "db_test",
    jdbcUrl:"jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&socketTimeout=60000"
  };
  proxy.resetForm("dbRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log(selection)
  ids.value = selection.map((item) => item.dsName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加product_func";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _productId = row.productId || ids.value;
  getProduct(_productId).then((response) => {
    form.value = response.data || {};
    open.value = true;
    title.value = "修改product_func";
  });
}

/** 提交按钮 */
function submitForm() {

  proxy.$refs["dbRef"].validate((valid) => {
    console.log({valid})
    if (valid) {
      if (form.value.productId != null) {
        updateDs(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDs(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _productIds = row.productId || ids.value;
  proxy.$modal
    .confirm('是否确认删除product_func编号为"' + _productIds + '"的数据项？')
    .then(function () {
      return delProduct(_productIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "finace/product/export",
    {
      ...queryParams.value,
    },
    `product_${new Date().getTime()}.xlsx`
  );
}

getList();

function handleDbPropertyChange(){
  Object.assign(form.value,{
    jdbcUrl: `jdbc:mysql://${form.value.dbIp}:3306/${form.value.dbName}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&socketTimeout=60000`
})
  // form.jdbcUrl = "jdbc:mysql://127.0.0.1:3306/fawcciot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&socketTimeout=60000"
}

function handleCreateTable1(row){
  const _productIds = row.productId || ids.value;

  console.log("handleCreateTable1", _productIds)
  const dsname = _productIds[0]
  console.log("handleCreateTable1", dsname)
  const sql = gen_table
  createTable({sql,dsname}).then((res)=>{
    console.log("createTable", res)
  })
}
function handleCreateTable2(row){
  const _productIds = row.productId || ids.value;

  console.log("handleCreateTable1", _productIds)
  const dsname = _productIds[0]
  console.log("handleCreateTable2", dsname)
  const sql = gen_table_column
  createTable({sql,dsname}).then((res)=>{
    console.log("createTable", res)
  })
}

</script>
